package me.jiatao.taobaotools.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import me.jiatao.taobaotools.R;
import me.jiatao.taobaotools.TaoBaoApp;
import me.jiatao.taobaotools.model.EvaluateCountItem;
import me.jiatao.taobaotools.utils.InJavaScriptLocalObj;
import me.jiatao.taobaotools.utils.ShowMessageUtils;
import me.jiatao.taobaotools.view.X5WebView;

public class ModifyEvaluateActivity extends BaseActivity {
    private boolean needModifyHtml = false;

    private X5WebView evaluateWevView;
    private View imageView;
    private View evaluateOption;

    private Button evaluateOptionOK;
    private EditText etWeek, etMonth, etSixMonth;

    private EvaluateCountItem evaluateCountItem;
    private String htmlString = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_evaluate);

        evaluateWevView = (X5WebView) findViewById(R.id.evaluateWevView);
        initWebView();
        initView();
    }

    private void initView() {
        Toast.makeText(activity, "点击顶部菜单栏弹出修改界面", Toast.LENGTH_SHORT).show();


        imageView =findViewById(R.id.evaluate_toolbar);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (evaluateOption.getVisibility() == View.VISIBLE) {
                    evaluateOption.setVisibility(View.GONE);
                } else {
                    evaluateOption.setVisibility(View.VISIBLE);
                }
            }
        });
        evaluateOption = findViewById(R.id.evaluate_option);
        evaluateOption.setVisibility(View.VISIBLE);

        etWeek = (EditText) findViewById(R.id.et_week);
        etMonth = (EditText) findViewById(R.id.et_month);
        etSixMonth = (EditText) findViewById(R.id.et_six_month);

        evaluateOptionOK = (Button) findViewById(R.id.evaluate_option_ok);
        evaluateOptionOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                evaluateCountItem = new EvaluateCountItem();

                if (TextUtils.isEmpty(etWeek.getText().toString())) {
                    ShowMessageUtils.show(activity, "最近一周不能为空");
                    return;
                } else {
                    evaluateCountItem.setWeek(Integer.parseInt(etWeek.getText().toString()));
                }
                if (TextUtils.isEmpty(etMonth.getText().toString())) {
                    ShowMessageUtils.show(activity, "最近一月不能为空");
                    return;
                } else {
                    evaluateCountItem.setMonth(Integer.parseInt(etMonth.getText().toString()));
                }

                if (TextUtils.isEmpty(etSixMonth.getText().toString())) {
                    ShowMessageUtils.show(activity, "最近六个月不能为空");
                    return;
                } else {
                    evaluateCountItem.setSixMonth(Integer.parseInt(etSixMonth.getText().toString()));
                }

                if (TextUtils.isEmpty(htmlString)) {
                    ShowMessageUtils.show(activity, "数据还未同步，请稍等");
                } else {
                    modifyHtml();
                }
            }
        });
    }

    private void initWebView() {
        WebSettings webSetting = evaluateWevView.getSettings();
        webSetting.setJavaScriptEnabled(true);

        //扩大比例的缩放
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        //自适应屏幕
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setLoadWithOverviewMode(true);

//        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSetting.setAppCacheEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setDomStorageEnabled(true);

        //webSetting.setUserAgentString("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36");

        evaluateWevView.addJavascriptInterface(new InJavaScriptLocalObj(activity, evaluateWevView), "java_obj");

        evaluateWevView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        evaluateWevView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(final WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (url.contains("rate.taobao.com") && needModifyHtml) {
                    needModifyHtml = false;
                    view.loadUrl("javascript:window.java_obj.getSource(document.documentElement.outerHTML);void(0)");
                }

            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });

        needModifyHtml = true;
//        evaluateWevView.loadUrl("https://rate.taobao.com/myRate.htm?spm=a1z09.2.a2109.d1000377.Je1Ct0&nekot=1449826612860");
        evaluateWevView.loadUrl("https://rate.taobao.com/user-myrate-UOmNLOmIWvGcG--buyerOrSeller%7C3--receivedOrPosted%7C1.htm");
//        evaluateWevView.loadUrl("file:////storage/emulated/0/2.html");
    }


//    public void loadEvaluate(View view) {
//        evaluateWevView.loadUrl("https://rate.taobao.com/myRate.htm?spm=a1z09.2.a2109.d1000377.Je1Ct0&nekot=1449826612860");
//    }


    @Override
    public void setWebViewHtml(final String strHtml) {
        htmlString = strHtml;
    }

    public void modifyHtml() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Document doc = Jsoup.parse(htmlString);

                    Element evaluateTable = doc.getElementsByClass("tb-rate-table align-c thm-plain").get(0);
                    Element evaluateTbody = evaluateTable.getElementsByTag("tbody").get(0);
                    Elements evaluateTRs = evaluateTbody.getElementsByTag("tr");
                    for (Element tr : evaluateTRs) {
                        evaluateCountItem.setEvaluateType(tr.child(0).text());

                        if (evaluateCountItem.getEvaluateType().equals("好评") || evaluateCountItem.getEvaluateType().equals("总计")) {
                            tr.child(1).html("<a href='#'>" + evaluateCountItem.getWeek() + "</a>");
                            tr.child(2).html("<a href='#'>" + evaluateCountItem.getMonth() + "</a>");
                            tr.child(3).html("<a href='#'>" + evaluateCountItem.getSixMonth() + "</a>");
                            evaluateCountItem.setSixMonthBrfor(Integer.parseInt(tr.child(4).text()));
                            tr.child(5).html("<a href='#'>" + evaluateCountItem.getTotal() + "</a>");


                        } else {
                            //清空中评和差评
                            tr.child(1).html("<a href='#'>0</a>");
                            tr.child(2).html("<a href='#'>0</a>");
                            tr.child(3).html("<a href='#'>0</a>");
                            tr.child(4).html("<a href='#'>0</a>");
                            tr.child(5).html("<a href='#'>0</a>");
                        }


                        Element rateListelEment = doc.getElementById("J_RateList");
                        if (rateListelEment != null) {
                            Elements rateItem = rateListelEment.getElementsByTag("tbody").get(0).getElementsByTag("tr");
                            for (int i = 0; i < rateItem.size(); i++) {
                                Element reviewContent = rateItem.get(i).getElementsByClass("J_ReviewContent").get(0);
                                Element dateElement = reviewContent.getElementsByClass("date").get(0);

                                String dateStr = getDateString(dateElement.text(), i);
                                dateElement.text(dateStr);
                            }
                        }
                    }

                    String htmlText = doc.html();
                    final String resHtml = htmlText.replace("\"//", "\"http://");

                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            TaoBaoApp.htmlString = resHtml;
                            evaluateWevView.loadData(resHtml, "text/html; charset=UTF-8", null);

                            ShowMessageUtils.show(activity, "修改完成");
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public String getDateString(String time, int index) {
        int weekCount = evaluateCountItem.getWeek();
        int monthCount = evaluateCountItem.getMonth();

        SimpleDateFormat sDateFormat = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]");
        try {
            Date date = sDateFormat.parse(time);

            Calendar nowCalendar = Calendar.getInstance();
            int hour = date.getHours();
            int minutes = date.getMinutes();
            int seconds = date.getSeconds();
            nowCalendar.set(Calendar.HOUR_OF_DAY, hour);
            nowCalendar.set(Calendar.MINUTE, minutes);
            nowCalendar.set(Calendar.SECOND, seconds);

            if (index < weekCount) {
                nowCalendar.add(Calendar.DAY_OF_MONTH, -(index + 1));
            } else {
                if (index < monthCount) {
                    nowCalendar.add(Calendar.DAY_OF_MONTH, -(index + 8));
                } else {
                    nowCalendar.add(Calendar.DAY_OF_MONTH, -(index + 30));
                }
            }

            return sDateFormat.format(nowCalendar.getTime());

        } catch (ParseException px) {
            px.printStackTrace();
        }

        return time;
    }
}
